<template>
   <ul class="list">
      <li
        class="item"
        v-for="item of letters"
        :key="item"
        @touchstart="handleTouchStart"
        @handleTouchMove="handleTouchMove"
        @handleTouchEnd="handleTouchEnd"
        @click="handleLetterClick"
        ref="item"
      >
        {{item}}
      </li>
   </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  // 把对象变为数组
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
      // ['A','B','C']
    }
  },
  data () {
    return {
      touchStatus: false,
      timer: null
    }
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    // 滑动次数多节流,每点一次清除之前的
    handleTouchMove (e) {
      let that = this
      if (that.touchStatus) {
        if (that.timer) {
          clearTimeout(that.timer)
        }
        that.timer = setTimeout(() => {
          const startY = that.$refs['A'][0].offsetTop
          const touchY = e.touches[0].clientY - 79
          const index = Math.floor((touchY - startY) / 20)
          // 再向外触发
          if (index >= 0 && index < that.letters.length) {
            that.$emit('change', that.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .list
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute
    top: 1.58rem
    right: 0
    bottom: 0
    width: .4rem
    .item
      line-height: .4rem
      text-align: center
      color: $bgColor
</style>
